const jwt=require('jsonwebtoken');
const {md5}=require('utility');
const query=require('../db/mysql')
const {sucess,error}=require('../modle/modle')



class User{
    Login=async(ctx)=>{
        const {username,password}=ctx.request.body;
        let sql=`select * from user where username='${username}' and password='${md5(String(password))}'`
        const data=await query(sql);
        console.log(data)
        if(data.length){
           ctx.body=sucess(
            {
               data:data[0],
               token:jwt.sign({id:data[0].id},'1812b')   //生成token 加密
            },
            '登录成功')
        }else{
            ctx.body=error('账号密码错误')
        }
    }
    Register=async(ctx)=>{
       const {username,password,nickname}=ctx.request.body;
       const isHave=await query(`select * from user where username='${username}'`);
       if(isHave.length){
           ctx.body=error('该账户已存在');
           return ;
       }
       let sql=`insert into user(username,password,nickname) values ('${username}','${md5(String(password))}','${nickname}')`
       const data=await query(sql);
       console.log(data)
       if(data.affectedRows>=1){
           ctx.body=sucess('注册成功')
       }else{
        ctx.body=error('注册失败');
       }
    }
}


module.exports=new User()